package com.heima.juc.n8;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author : leimingchao
 * @date Date : 2022年02月19日 22:07
 */
@Slf4j(topic = "c.TestSchedule")
public class TestSchedule {

    /**
     * 如何让每周四18:00:00定时执行任务？
     * @param args
     */
    public static void main(String[] args) {

        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        //initalDelay代表当前时间和周四的时间差
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //获取周四时间
        LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
        //如果当前时间 > 本周周四，必须找到下周周四
        if (now.isAfter(time)) {
            time = time.plusWeeks(1);
        }
        long initialDelay = Duration.between(now, time).toMillis();
        //period一周的时间间隔
        long period = 1000 * 60 * 60 * 24 * 7;
        pool.scheduleAtFixedRate(() -> {
            log.debug("running...");
        }, initialDelay, period, TimeUnit.MILLISECONDS);
    }
}
